package com.jy.unkown.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amjy.dsl.R;
import com.bumptech.glide.Glide;
import com.jiayou.ziyou_ad.utils.MD5Util;
import com.jy.common.BaseApplication;
import com.jy.unkown.PlayStartPauseListener;
import com.jy.unkown.UnkownVideoPoint;
import com.jy.unkown.UnkownVideoPoint2;
import com.jy.unkown.WebActivty;
import com.jy.unkown.entity.UnkownAdBean;
import com.jy.utils.cache.SpManager;
import com.jy.utils.utils.ApkUtils;
import com.jy.utils.utils.UI;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class UnkownFeedView extends UnkownADView implements View.OnClickListener {


    public UnkownFeedView(@NonNull Context context) {
        super(context);
    }

    public UnkownFeedView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public UnkownFeedView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    TextView progressText;
    UnkowVideoView unkowVideoView;
    UnkownVideoPoint2 unkownVideoPoint;

    @Override
    public void show() {
        setTAG("信息流广告");
        if (baseUnkownAd == null) {
            err();
            return;
        }
        View view = LayoutInflater.from(getContext()).inflate(R.layout.unkown_native_view, null);
        UnkownAdBean unkownAdBean = baseUnkownAd;
        String adlogo = unkownAdBean.adlogo;
        ImageView logoImg = view.findViewById(R.id.img_logo);
        Glide.with(getContext()).load(adlogo).into(logoImg);
        progressText = view.findViewById(R.id.btn_download);
        ImageView native_main_image = view.findViewById(R.id.native_main_image);
        View adclose = view.findViewById(R.id.adclose);

        adclose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewGroup viewGroup = (ViewGroup) getParent();
                if (viewGroup != null) {
                    viewGroup.removeView(UnkownFeedView.this);
                    onDestory();
                    adClose();
                }
            }
        });

        TextView native_text = view.findViewById(R.id.text_desc);

        if (unkownAdBean.metaGroup != null && unkownAdBean.metaGroup.size() > 0) {
            UnkownAdBean.MetaGroupDTO metaGroupDTO = unkownAdBean.metaGroup.get(0);
            List<String> descs = metaGroupDTO.descs;
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < descs.size(); i++) {
                stringBuffer.append(descs.get(i)).append("\n");
            }
            native_text.setText(stringBuffer.toString());
            TextView native_brand_name = view.findViewById(R.id.native_brand_name);
            native_brand_name.setText(metaGroupDTO.brandName);
            if (metaGroupDTO.creativeType == 1) {
                //文字
                view.findViewById(R.id.ghost_vi).setVisibility(GONE);
                List<String> images = metaGroupDTO.imageUrl;
                if (images != null && images.size() > 0) {
                    Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                }
            } else if (metaGroupDTO.creativeType == 2) {//

                List<String> images = metaGroupDTO.imageUrl;
                if (images != null && images.size() > 0) {
                    Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                }
            } else if (metaGroupDTO.creativeType == 5) {
                ViewStub viewStub = view.findViewById(R.id.videoStub);
                View vv = viewStub.inflate();
                List<String> images = metaGroupDTO.imageUrl;
                if (images != null && images.size() > 0) {
                    Glide.with(getContext()).load(images.get(0)).into(native_main_image);
                }

                unkowVideoView = vv.findViewById(R.id.unkownVideoView);
                unkowVideoView.setUrl(metaGroupDTO.videoUrl);
//                unkowVideoView.muteVoice(videoMute);
                unkowVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        List<String> winloadUrls = metaGroupDTO.winLoadUrls;
                        pointPost(UnkownADView.PLAY_VIDEO, "winloadUrls 视频加载成功", winloadUrls);
                        native_main_image.setVisibility(GONE);
                    }
                });
                unkownVideoPoint = new UnkownVideoPoint2(this, unkowVideoView, unkownAdBean.tracks);
                unkownVideoPoint.init();
//                unkowVideoView.setPlayStartPauseListener(new PlayStartPauseListener() {
//                    @Override
//                    public void onStop() {
//                        List<UnkownAdBean.TracksDTO> tracks = unkownAdBean.tracks;
//                        if (tracks != null) {
//                            for (int i = 0; i < tracks.size(); i++) {
//                                UnkownAdBean.TracksDTO tracksDTO = tracks.get(i);
//                                if (tracksDTO != null) {
//                                    if (tracksDTO.type == 107) {
//                                        pointPost(UnkownADView.PLAY_VIDEO, "107-视频暂停播放 ", tracksDTO.urls);
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onStart() {
//                        List<UnkownAdBean.TracksDTO> tracks = unkownAdBean.tracks;
//                        if (tracks != null) {
//                            for (int i = 0; i < tracks.size(); i++) {
//                                UnkownAdBean.TracksDTO tracksDTO = tracks.get(i);
//                                if (tracksDTO != null) {
//                                    if (tracksDTO.type == 108) {
//                                        pointPost(UnkownADView.PLAY_VIDEO, "108-视频暂停后继续播放", tracksDTO.urls);
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                });
                UI.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        unkowVideoView.playVideo();
                    }
                }, 1000);
            }


            if (metaGroupDTO.interactionType == 3) {//进入下载页面
                progressText.setText("查看详情");
            } else if (metaGroupDTO.interactionType == 2) {//下载类
                boolean isInstall = ApkUtils.isInstall(metaGroupDTO.packageName);
                if (isInstall) {
                    progressText.setText("点击打开");
                } else {
                    if (metaGroupDTO != null) {
                        String downUrl = metaGroupDTO.clickUrl;
                        String key = MD5Util.getMD5(downUrl);
                        String path = SpManager.getString(key, "");
                        if (TextUtils.isEmpty(path)) {
                            progressText.setText("点击下载");
                        } else {
                            if (ApkUtils.checkApkFileIsVaild(path)) {
                                progressText.setText("点击安装");
                            } else {
                                progressText.setText("点击下载");
                            }
                        }
                    }
                }

                native_brand_name.setText(metaGroupDTO.brandName);

            } else if (metaGroupDTO.interactionType == 1) {//跳转类
                progressText.setText("查看详情");
            }


        }
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        addView(view, layoutParams);
        setOnClickListener(this);
        UnkownAdBean.MetaGroupDTO metaGroupDTO = getMetaGroupDTOBean();
        if (metaGroupDTO != null) {
            exposure(metaGroupDTO.winNoticeUrls);
        }
    }


    boolean isAttachedToWindow = false;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        isAttachedToWindow = true;
        Log.e(getClass().getSimpleName(), "onAttachedToWindow");
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isAttachedToWindow = false;
        if (unkowVideoView != null) {
            unkowVideoView.onPause();
        }
        Log.e(getClass().getSimpleName(), "onDetachedFromWindow");
    }


    @Override
    void downloadSucc(String url, File progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载完成");
                }
            });
        }
    }

    @Override
    void downloadErr(String url, Exception e) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载失败");
                }
            });
        }
    }

    @Override
    void downloadProgress(String url, int progress) {
        if (progressText != null && isAttachedToWindow) {
            UI.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    progressText.setText("下载" + progress + "%");
                }
            });
        }
    }


    public void onDestory() {
        try {
            unkownVideoPoint.setStart(false);
            unkowVideoView.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
